<template>
  <div class="ibox">
    <link href="/css/plugins/morris/morris-0.4.3.min.css" rel="stylesheet">
    <div class="ibox-title">
      <h4>{{ title }}</h4>
    </div>
    <div class="ibox-content">
      <div :id="p_id">
        <canvas height="130" :id="id"></canvas>
      </div>
    </div>
  </div>
</template>

<script>
export default {
	name: 'lineChart',
	props: {
		id: String,
		title: String,
		labelsSet: Array,
		chartData: Object,
		y_keys: Array,
		x_keys: null
	},
	data() {
		return {
			chart: null,
			p_id: this.id + '_p',
			lineColors: [
				'rgba(255,218,185,0.5)',
				'rgba(255,193,193,0.5)',
				'rgba(255,193,37,0.5)',
				'rgba(72,118,255,0.5)',
				'rgba(255,0,0,0.5)',
				'rgbs(0,255,0,0.5)',
				'rgba(0,0,0,0.5)',
				'rgba(105,105,105,0.5)',
				'rgba(85,26,139,0.5)',
				'rgba(0,139,139,0.5)',
				'rgba(255,0,255,0.5)',
				'rgba(255,250,205,0.5)',
				'rgba(255,99,71,0.5)'
			]
		};
	},
	methods: {
		draw: function(data) {
			if (data == null) {
				data = this.chartData;
				// console.log(data);
				// console.log(data[this.id][this.y_keys[0]]);
			}

			var dataSet = [];
			for (var i = 0; i < this.labelsSet.length; i++) {
				dataSet.push({
					label: this.labelsSet[i],
					backgroundColor: this.lineColors[i],
					borderColor: 'rgba(26,179,148,0.7)',
					pointBackgroundColor: 'rgba(26,179,148,1)',
					pointBorderColor: '#fff',
					data: data[this.id][this.y_keys[i]]
				});
			}

			// console.log('dataSet', dataSet);
			// console.log('data', data);
			var lineData;
			if (this.x_keys) {
				lineData = {
					labels: data.week,
					datasets: dataSet
				};
			} else {
				lineData = {
					labels: data.date,
					datasets: dataSet
				};
			}
			var lineOptions = {
				responsive: true
			};
			if (this.chart) {
				var chartDivId = this.id;
				if (!!document.getElementById(chartDivId)) {
					document.getElementById(chartDivId).remove();
				}
				var cdom = document.createElement('canvas');

				cdom.setAttribute('id', chartDivId);
				cdom.setAttribute('height', '120');
				document.getElementById(chartDivId + '_p').appendChild(cdom);
				var canvas = document.getElementById(chartDivId);
				var ctx = canvas.getContext('2d');
				//ctx.clearRect(0,0,canvas.width,canvas.height);
				this.chart = new Chart(ctx, {
					type: 'line',
					data: lineData,
					options: lineOptions
				});
				return;
			}

			var ctx = document.getElementById(this.id).getContext('2d');
			// console.log(lineData);
			this.chart = new Chart(ctx, {
				type: 'line',
				data: lineData,
				options: lineOptions
			});
		},
		update_data: function(data) {
			this.draw(data);
		}
	},
	mounted() {
		// setTimeout(this.draw, 2000);
		this.draw(null);
	}
};
</script>

<style scoped>
</style>
